<template>
  <view class="container">
    <!-- 用户信息区域 -->
    <view class="user-section" v-if="isLoggedIn">
      <view class="user-info">
        <view class="avatar-col">
          <image class="avatar" :src="userInfo.avatarUrl || '/static/logo.png'" mode="aspectFill" @click="changeAvatar" />
        </view>
        <view class="user-details">
          <text class="username">{{ userInfo.nickname || userInfo.username }}</text>
          <text class="user-desc">音乐爱好者</text>
        </view>
      </view>
      <view class="user-stats">
        <view class="stat-item">
          <text class="stat-number">{{ favoritesCount }}</text>
          <text class="stat-label">收藏</text>
        </view>
        <view class="stat-item">
          <text class="stat-number">{{ historyCount }}</text>
          <text class="stat-label">播放</text>
        </view>
      </view>
    </view>

    <!-- 未登录状态 -->
    <view class="login-section" v-else>
      <image class="login-avatar" src="/static/default-avatar.png" mode="aspectFill" />
      <text class="login-text">登录后享受更多功能</text>
      <button class="login-btn" @click="goToLogin">立即登录</button>
    </view>

    <!-- 功能菜单 -->
    <view class="menu-section">
      <view class="menu-item" @click="goToFavorites" v-if="isLoggedIn">
        <text class="menu-icon">❤️</text>
        <text class="menu-text">我的收藏</text>
        <text class="menu-arrow">></text>
      </view>
      
      <view class="menu-item" @click="goToHistory" v-if="isLoggedIn">
        <text class="menu-icon">🕒</text>
        <text class="menu-text">播放历史</text>
        <text class="menu-arrow">></text>
      </view>
      
      <view class="menu-item" @click="goToSettings">
        <text class="menu-icon">⚙️</text>
        <text class="menu-text">设置</text>
        <text class="menu-arrow">></text>
      </view>
      
      <view class="menu-item" @click="goToAbout">
        <text class="menu-icon">ℹ️</text>
        <text class="menu-text">关于我们</text>
        <text class="menu-arrow">></text>
      </view>
      
      <view class="menu-item logout-btn" @click="logout" v-if="isLoggedIn">
        <text class="menu-icon">🚪</text>
        <text class="menu-text">退出登录</text>
        <text class="menu-arrow">></text>
      </view>
    </view>

    <!-- 底部播放器 -->
    <view class="mini-player" v-if="currentSong" @click="goToPlayer">
      <image class="mini-player-cover" :src="currentSong.cover_image_url" mode="aspectFill" />
      <view class="mini-player-info">
        <text class="mini-player-name">{{ currentSong.name }}</text>
        <text class="mini-player-artist">{{ currentSong.artist_name }}</text>
      </view>
      <view class="mini-player-controls">
        <text class="control-btn" @click.stop="togglePlay">
          {{ isPlaying ? '⏸️' : '▶️' }}
        </text>
        <text class="control-btn" @click.stop="nextSong">⏭️</text>
      </view>
    </view>
  </view>
</template>

<script>
import { api } from '/utils/api.js'

const BASE_URL = 'http://localhost:3000/api'

// 简化的音乐播放器
class SimpleMusicPlayer {
  constructor() {
    this.audioContext = null
    this.currentSong = null
    this.isPlaying = false
    this.playlist = []
    this.currentIndex = 0
  }

  init() {
    this.audioContext = uni.createInnerAudioContext()
    this.audioContext.onPlay(() => {
      this.isPlaying = true
    })
    this.audioContext.onPause(() => {
      this.isPlaying = false
    })
  }

  play(song) {
    if (!song) return
    this.currentSong = song
    this.audioContext.src = song.file_url
    this.audioContext.play()
  }

  togglePlay() {
    if (this.isPlaying) {
      this.audioContext.pause()
    } else {
      this.audioContext.play()
    }
  }

  setPlaylist(playlist, index = 0) {
    this.playlist = playlist
    this.currentIndex = index
    if (playlist.length > 0) {
      this.play(playlist[index])
    }
  }

  next() {
    if (this.playlist.length === 0) return
    this.currentIndex = this.currentIndex < this.playlist.length - 1 ? this.currentIndex + 1 : 0
    this.play(this.playlist[this.currentIndex])
  }

  getCurrentInfo() {
    return {
      song: this.currentSong,
      isPlaying: this.isPlaying,
      playlist: this.playlist,
      currentIndex: this.currentIndex
    }
  }
}

const musicPlayer = new SimpleMusicPlayer()

export default {
  data() {
    return {
      isLoggedIn: false,
      userInfo: {},
      favoritesCount: 0,
      historyCount: 0,
      currentSong: null,
      isPlaying: false
    }
  },

  onLoad() {
    this.checkLoginStatus()
    this.updatePlayerState()
  },

  onShow() {
    this.checkLoginStatus()
    this.updatePlayerState()
    if (this.isLoggedIn) {
      this.loadUserData()
    }
  },

  methods: {
    // 检查登录状态
    checkLoginStatus() {
      const token = uni.getStorageSync('token')
      const userInfo = uni.getStorageSync('userInfo')
      
      if (token && userInfo) {
        this.isLoggedIn = true
        this.userInfo = userInfo
      } else {
        this.isLoggedIn = false
        this.userInfo = {}
      }
    },

    // 更新播放器状态
    updatePlayerState() {
      const playerInfo = musicPlayer.getCurrentInfo()
      this.currentSong = playerInfo.song
      this.isPlaying = playerInfo.isPlaying
    },

    // 加载用户数据
    async loadUserData() {
      try {
        // 获取用户信息
        const profileRes = await api.user.getProfile()
        this.userInfo = profileRes.data

        // 获取收藏数量
        const favoritesRes = await api.music.getFavorites()
        this.favoritesCount = favoritesRes.data.length

        // 获取播放历史数量
        const historyRes = await api.music.getHistory()
        this.historyCount = historyRes.data.length
      } catch (error) {
        console.error('加载用户数据失败:', error)
        // 如果用户未登录，重置数据
        if (error.code === 401) {
          this.isLoggedIn = false
          this.userInfo = {}
          this.favoritesCount = 0
          this.historyCount = 0
        }
      }
    },

    // 跳转到登录页面
    goToLogin() {
      uni.navigateTo({
        url: '/pages/login/login'
      })
    },

    // 跳转到收藏页面
    goToFavorites() {
      uni.navigateTo({
        url: '/pages/favorites/favorites'
      })
    },

    // 跳转到播放历史页面
    goToHistory() {
      uni.navigateTo({
        url: '/pages/history/history'
      })
    },

    // 跳转到设置页面
    goToSettings() {
      uni.navigateTo({
        url: '/pages/settings/settings'
      })
    },

    // 跳转到关于页面
    goToAbout() {
      uni.navigateTo({
        url: '/pages/about/about'
      })
    },

    // 退出登录
    logout() {
      uni.showModal({
        title: '确认退出',
        content: '确定要退出登录吗？',
        success: (res) => {
          if (res.confirm) {
            // 清除本地存储
            uni.removeStorageSync('token')
            uni.removeStorageSync('userInfo')
            
            // 更新状态
            this.isLoggedIn = false
            this.userInfo = {}
            this.favoritesCount = 0
            this.historyCount = 0
            
            uni.showToast({
              title: '已退出登录',
              icon: 'success'
            })
          }
        }
      })
    },

    // 切换播放状态
    togglePlay() {
      musicPlayer.togglePlay()
    },

    // 下一首
    nextSong() {
      musicPlayer.next()
    },

    // 跳转到播放器页面
    goToPlayer() {
      uni.navigateTo({
        url: '/pages/player/player'
      })
    },

    // 更换头像
    async changeAvatar() {
      try {
        const chooseRes = await new Promise((resolve, reject) => {
          uni.chooseImage({
            count: 1,
            sizeType: ['compressed'],
            sourceType: ['album', 'camera'],
            success: resolve,
            fail: reject
          })
        })

        const filePath = chooseRes.tempFilePaths[0]
        if (!filePath) return

        const token = uni.getStorageSync('token')

        const uploadRes = await new Promise((resolve, reject) => {
          uni.uploadFile({
            url: BASE_URL + '/users/avatar',
            filePath,
            name: 'file',
            header: {
              'Authorization': token ? `Bearer ${token}` : ''
            },
            success: (res) => {
              // 兼容后端返回非 JSON 的情况
              let data = res.data
              try {
                if (typeof data === 'string') data = JSON.parse(data)
              } catch (e) {
                // 如果不是 JSON，包装成对象继续走错误提示
                return reject({ code: res.statusCode, message: '上传响应解析失败' })
              }
              if (res.statusCode === 200) {
                resolve(data)
              } else {
                reject(data)
              }
            },
            fail: reject
          })
        })

        // 更新本地用户信息与展示
        if (uploadRes && uploadRes.data && uploadRes.data.avatarUrl) {
          this.userInfo.avatarUrl = uploadRes.data.avatarUrl
          uni.setStorageSync('userInfo', this.userInfo)
          uni.showToast({ title: '头像已更新', icon: 'success' })
        }

      } catch (err) {
        console.error('更换头像失败:', err)
        uni.showToast({ title: err.message || '更换失败', icon: 'none' })
      }
    }
  }
}
</script>

<style scoped>
.container {
  padding: 20rpx;
  background-color: #f8f8f8;
  min-height: 100vh;
}

.user-section {
  background-color: white;
  border-radius: 20rpx;
  padding: 40rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.user-info {
  display: flex;
  align-items: center;
  margin-bottom: 30rpx;
}
.avatar-col {
  display: flex;
  flex-direction: column;
  align-items: center;
}


.avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 60rpx;
  margin-right: 30rpx;
}

.user-details {
  flex: 1;
}

.username {
  display: block;
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
}

.user-desc {
  display: block;
  font-size: 26rpx;
  color: #999;
}

.user-stats {
  display: flex;
  justify-content: space-around;
}

.stat-item {
  text-align: center;
}

.stat-number {
  display: block;
  font-size: 36rpx;
  font-weight: bold;
  color: #ff6b6b;
  margin-bottom: 10rpx;
}

.stat-label {
  display: block;
  font-size: 24rpx;
  color: #999;
}

.login-section {
  background-color: white;
  border-radius: 20rpx;
  padding: 60rpx 40rpx;
  margin-bottom: 30rpx;
  text-align: center;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.login-avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 60rpx;
  margin-bottom: 30rpx;
}

.login-text {
  display: block;
  font-size: 28rpx;
  color: #666;
  margin-bottom: 40rpx;
}

.login-btn {
  background-color: #ff6b6b;
  color: white;
  border-radius: 40rpx;
  padding: 20rpx 60rpx;
  font-size: 28rpx;
  border: none;
}

.menu-section {
  background-color: white;
  border-radius: 20rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.menu-item:last-child {
  border-bottom: none;
}

.menu-item.logout-btn {
  color: #ff6b6b;
}

.menu-icon {
  font-size: 40rpx;
  margin-right: 30rpx;
  width: 40rpx;
  text-align: center;
}

.menu-text {
  flex: 1;
  font-size: 28rpx;
  color: #333;
}

.logout-btn .menu-text {
  color: #ff6b6b;
}

.menu-arrow {
  font-size: 24rpx;
  color: #ccc;
}

.mini-player {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 120rpx;
  background-color: white;
  display: flex;
  align-items: center;
  padding: 0 30rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
  z-index: 1000;
}

.mini-player-cover {
  width: 80rpx;
  height: 80rpx;
  border-radius: 10rpx;
  margin-right: 20rpx;
}

.mini-player-info {
  flex: 1;
}

.mini-player-name {
  display: block;
  font-size: 26rpx;
  color: #333;
  margin-bottom: 5rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.mini-player-artist {
  display: block;
  font-size: 22rpx;
  color: #999;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.mini-player-controls {
  display: flex;
  align-items: center;
}

.control-btn {
  font-size: 40rpx;
  margin-left: 20rpx;
  padding: 10rpx;
}
</style>
